/*  
cd /projects/data_commons/lbd_code/
qsas lbd_1_raw_fk_aux.sas 5 &
*/

libname llbd "/projects/data_commons/lbd/";
%Let dir_llbd = /projects/data_commons/lbd/;

/* Macro that reads in auxiliary data set */

%macro read_lbd(i_year= );

/* REDACTED
libname raw has been redacted */
libname raw "/REDACTED/";

%put ================================================================================;
%put Year &i_year.;
%put --------------------------------------------------------------------------------;

%Let yver=2016;

%Let naics_keep=lbdid fk_naics02;


data dti_aux;
  set raw.naics&i_year._aux_c&yver.00 (keep=&naics_keep.);
  year = &i_year.;
run;

data dti_aux;
  set dti_aux;
run;

%if %sysfunc(exist(dt_aux)) %then %do;
  data dt_aux;
    set dt_aux dti_aux;
  run;
%end;
%else %do;
  data dt_aux;
    set dti_aux;
  run;
%end;

%mend;

/* Macro that executes */

%macro main_read_lbd();
  %Let i_year=1976;
  %do %while(%eval(&i_year.)<=2001); /* Last SIC year */
    %read_lbd(i_year=&i_year.)
    %Let i_year = %eval(&i_year. + 1);
  %end;
%mend;

%main_read_lbd();

proc sort data=dt_aux; by year lbdid;

data dt_aux;
  set dt_aux;
  aux_fk_naics = substr(fk_naics02,1,6)*1;
  drop fk_naics02;
run;

/*
--------------------------------------------------------------------------------
Merge with industry crosswalk
*/

proc import out=cross datafile="/projects/data_commons/cw/cw_ind_fk_imp.csv";
run;

data cross;
  set cross;
  rename fk_naics=aux_fk_naics ch_ind=aux_ch_ind;
run;

proc sort data=cross; by aux_fk_naics;
proc sort data=dt_aux; by aux_fk_naics;

data dt_aux;
  merge dt_aux(in=x) cross(in=y);
  by aux_fk_naics;
  if x = 1;
run;

/*
--------------------------------------------------------------------------------
Export
*/

proc sort data=dt_aux; by year lbdid;

data llbd.lbd_raw_fk_aux;
  set dt_aux;
run;

proc export data=dt_aux outfile="&dir_llbd./lbd_raw_fk_aux.dta" replace;
run;

/* End of do file */
